/*
 * Copyright 2022 Institute of Software Chinese Academy of Sciences, ISRC
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
import router from '@system.router';
import http from '@ohos.net.http';
import prompt from '@system.prompt';

export default {
    data: {
        titleText:'',
        listTitleText:'',
        displayGroupName:false,
        friendsList: [], // 显示列表
        checkedId: [],
        groupName:'',
        groupId:'',
        operation:'create', // 测试时写入默认值
        re:{
            code:"",
            msg:"",
            data:""
        },
    },
    onInit() {
        if(router.getParams() && router.getParams().operation) {
            this.operation = router.getParams().operation; //操作类型，invite表示邀请进群操作
        } else {
            this.operation = 'create'
        }
        if(this.operation == 'invite'){
            this.friendsList = this.$app.$def.friendsList
            this.titleText = '邀请加入群聊';
            this.listTitleText = '我的联系人';
            this.groupId=router.getParams().groupId;
        } else if(this.operation == 'create'){  //create表示建群
            this.friendsList = this.$app.$def.friendsList
            this.titleText = '发起群聊';
            this.listTitleText = '我的联系人';
            this.displayGroupName = true;
            this.groupId = this.getRandomSixDigit()
        }else if(this.operation == 'delete'){
            this.friendsList = this.$app.$def.groupMembersList
            this.titleText = '移除群成员';
            this.listTitleText = '群成员列表';
            this.groupId=router.getParams().groupId;
        }
    },
    onShow() {

    },
    backToSession(){
        router.back();
    },
    checkFriends(e){
        let uid = e.target.attr.value
        if (this.checkedId.indexOf(uid) > -1) {
            this.checkedId.splice(this.checkedId.indexOf(uid), 1)
        } else {
            this.checkedId.push(uid)
        }
    },
    change(e){
        this.groupName = e.value;
    },
    finishButton(){
        if(this.operation == 'create'){
            console.info("finishButton ====> createGroup");
            this.createGroup();
        } else if(this.operation == 'invite'){
            console.info("finishButton ====> inviteMembersToGroup");
            this.inviteMembersToGroup();
        } else if(this.operation == 'delete'){
            console.info("finishButton ====> deleteMembersFromGroup");
            this.deleteMembersFromGroup();
        }
    },
    createGroup() {
        console.info("createGroup====> params : " +JSON.stringify({"uid":this.$app.$def.uid,"groupId":this.groupId,"groupName":this.groupName,"checkId":this.checkedId,}));
        this.$app.$def.checkedId = this.checkedId
        this.addSession();
//        TODO  未完成
        let httpRequest= http.createHttp();
        let promise = httpRequest.request("http://" + this.$app.$def.ip +"/group/createGroup", {
            method: 'POST',
            extraData:JSON.stringify({"uid":this.$app.$def.uid,"groupId":this.groupId,"groupName":this.groupName,"checkId":this.checkedId,}),
            connectTimeout: 60000,
            readTimeout: 60000,
            header: {
                'Content-Type': 'application/json'
            }
        });
        promise.then((value) => {
            prompt.showToast({
                message: '发送成功！',
                duration: 2000,
            });
            console.info('createGroup====> value.result: ' + value.result);
            let result= JSON.parse(value.result.toString())
            console.info('createGroup====> result ' + result);
            console.info('createGroup====> value.responseCode: ' + value.responseCode);
            console.info('createGroup====> value.header: ' + value.header);
            if(result.code == 200){
                prompt.showToast({
                    message: '创建成功！',
                    duration: 2000,
                });
                router.push({
                    uri: "pages/dialogPage/dialogPage",
                    params: {
                        sayOrGroup: 'group',
                        sayOrGroup_ID: this.groupId,
                        type: 'createGroup'
                    }
                })
            } else {
                prompt.showToast({
                    message: '创建失败！' + result.code,
                    duration: 2000,
                });
            }
        }).catch((err) => {
            console.error(`createGroup====> errCode:${err.code}, errMessage1:${err.data}`);
        });
    },
    getRandomSixDigit(){
        let code = ''
        for(var i=0;i<6;i++){
            code += parseInt(Math.random()*10)
        }
        return code
    },
    inviteMembersToGroup(){
        console.info("inviteMembersToGroup====> checkedId : " +this.checkedId);
        this.$app.$def.checkedId = this.checkedId
        let httpRequest= http.createHttp();
        let promise = httpRequest.request("http://" + this.$app.$def.ip +"/group/invite", {
            method: 'POST',
            extraData:JSON.stringify({"uid":this.$app.$def.uid,"inviteUids":this.checkedId,"groupId":this.groupId}),
            connectTimeout: 60000,
            readTimeout: 60000,
            header: {
                'Content-Type': 'application/json'
            }
        });
        promise.then((value) => {
            let re = JSON.parse(value.result.toString())
            if(re.code == 2029){
                prompt.showToast({
                    message: '邀请成功',
                    duration: 2000,
                });
            } else if(re.code == 2030){
                prompt.showToast({
                    message: '邀请失败',
                    duration: 2000,
                });
            }
        }).catch((err) => {
            console.error(`inviteMembersToGroup====> errCode:${err.code}, errMessage1:${err.data}`);
        });
        router.back();
    },
    deleteMembersFromGroup(){
        console.info("inviteMembersToGroup====> checkedId : " +this.checkedId);
        this.$app.$def.checkedId = this.checkedId
        let httpRequest= http.createHttp();
        let promise = httpRequest.request("http://" + this.$app.$def.ip +"/group/kickOut", {
            method: 'POST',
            extraData:JSON.stringify({"uid":this.$app.$def.uid,"kickOutUids":this.checkedId,"groupId":this.groupId}),
            connectTimeout: 60000,
            readTimeout: 60000,
            header: {
                'Content-Type': 'application/json'
            }
        });
        promise.then((value) => {
            let re = JSON.parse(value.result.toString())
            if(re.code == 2031){
                prompt.showToast({
                    message: '踢出成功',
                    duration: 2000,
                });
            } else if(re.code == 2032){
                prompt.showToast({
                    message: '踢出失败',
                    duration: 2000,
                });
            }
        }).catch((err) => {
            console.error(`inviteMembersToGroup====> errCode:${err.code}, errMessage1:${err.data}`);
        });
        router.back();
    },
    addSession(){
        let img = '/common/images/sessionPic/img_' + Math.round(Math.random()*7+1) + '.png'
        let newSession = {
            'title': this.groupName,
            'topMessage': '群聊已经成功创建！',
            'imgUrl': img,
            'readTime': new Date().getHours() + ':' + new Date().getMinutes(),
            'unRead': 'group',
            'uid':[this.groupId],
            'checkId':this.checkedId,
            'MsgList': [{isMe: false,
                            sendUid:"",
                            messageType: 0,
                            content:'华为鸿蒙系统是一款全新的面向全场景的分布式操作系统，创造一个超级虚拟终端互联的世界',
                            profPicUrl:'/common/images/bob.jpg',
                            createTime:"",},
                        {isMe: false,
                            sendUid:"",
                            messageType: 1,
                            content:'/common/images/harmonyos.jpg',
                            profPicUrl:'/common/images/bob.jpg',
                            createTime:"",}]
        }
        this.$app.$def.chatData=[newSession,...this.$app.$def.chatData]
    },
}